using System;
using Microsoft.ApplicationServer.Caching;
using Orchard.Logging;

namespace Contrib.AppFabric.Configuration {
    public class AppFabricClient : IAppFabricClient {
        public AppFabricClient() {
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        // Track whether Dispose has been called.
        private bool _disposed = false;

        // I think its right to share the same instance across tenants.
        private static readonly Lazy<DataCacheFactory> LazyDataCacheFactory = new Lazy<DataCacheFactory>(() => new DataCacheFactory());
        private static DataCacheFactory DataCacheFactory { get { return LazyDataCacheFactory.Value; } }

        private static readonly object SyncLock = new object();
        private volatile DataCache _dataCache;

        public DataCache GetCache(string cacheName) {
            EnsureCache(cacheName);

            return _dataCache;
        }

        private void EnsureCache(string cacheName) {
            if (_dataCache == null) {
                lock (SyncLock) {
                    if (_dataCache == null) {
                        _dataCache = DataCacheFactory.GetCache(cacheName);
                    }
                }
            }
        }

        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing) {
            if (!this._disposed) {
                if (disposing) {
                    try {
                        DataCacheFactory.Dispose(); // Will ISingleDependency shut down by errr tenant?
                    }
                    catch (Exception ex) {
                        Logger.Error(ex, "DataCacheFactory cannot be disposed as it hasn't been initialized.");
                    }
                }
                _disposed = true;
            }
        }

        ~AppFabricClient()
        {
            Dispose(false);
        }
    }
}